#ifndef RTSPSERVER2_H
#define RTSPSERVER2_H

#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QUdpSocket>
#include <QDebug>
#include <QFile>
#include <QDataStream>
#include <QThread>

#include "rtsp.h"
#include "rtppacket.h"
#include "helper.h"

#define SERVER_PORT         8554
#define SERVER_RTP_PORT     55532
#define SERVER_RTCP_PORT    55533

#define H264_FILE_NAME      "D:/ffmpeg/test.h264"

class RtspServer2 : public QObject
{
    Q_OBJECT
public:
    explicit RtspServer2(QObject *parent = nullptr);
    ~RtspServer2();

public slots:
    void start();
    void OnNewConnection();
    void OnRecv();
    void OnMessage(QString recvMsg);
    void OnClosed();

    int OnCreatUdpSocket();

    int handleCmd_OPTIONS(char* result, int cseq);
    int handleCmd_DESCRIBE(char* result, int cseq, char* url);
    int handleCmd_SETUP(char* result, int cseq, int clientRtpPort);
    int handleCmd_PLAY(char* result, int cseq);

    int getFrameFromH264File(char *frame, int len);
    /**
     * @brief startCode3 h264文件NAUL的分隔"00 00 01"
     * @param buf
     * @return
     */
    int startCode3(char* buf);
    /**
     * @brief startCode4 h264文件NAUL的分隔"00 00 00 01"
     * @param buf
     * @return
     */
    int startCode4(char* buf);
    /**
     * @brief findNextStartCode
     * @param buf
     * @param len
     * @return
     */
    char* findNextStartCode(char* buf, int len);

    int rtpSendH264Frame(struct RtpPacket* rtpPacket, char* frame, uint32_t frameSize);

private:
    QTcpServer *m_server;
    QTcpSocket *m_socket;
    QString clientIP;
    int clientPort;

    QUdpSocket *m_rtpSocket;
    QUdpSocket *m_rtcpSocket;

    bool m_bConnected;

    QFile h264File;
    qint64 offsetPos;
};

#endif // RTSPSERVER2_H
